﻿using System;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using XamlingCore.SL.Controls.Lists.Lazy;

namespace XamlingCore.SL.Controls.Lists.Grouping
{
    [TemplatePart(Name = "GroupTitleArea", Type = typeof(ContentControl))]
    public class XGroupingListBox : XLazyListBox
    {
        private ContentControl groupTitleArea;

        protected override void DoRelocation()
        {
            base.DoRelocation();

            if (ItemsSource != null)
            {
                var list = this.ItemsSource.OfType<object>().ToList();

                if (list != null && list.Count > 0)
                {
                    double location = Scroller.VerticalOffset;

                    double extent = Scroller.ExtentHeight;

                    double vpHeight = Scroller.ViewportHeight;

                    var item = list[Convert.ToInt32(location)] as IGroupableItem;

                    if (item != null && GroupTitleArea != null)
                    {
                        if (GroupTitleArea.Content != item)
                        {
                            GroupTitleArea.Content = item;
                        }
                    }
                }
            }
        }

        public override void OnApplyTemplate()
        {
            GroupTitleArea = GetTemplateChild("GroupTitleArea") as ContentControl;
            base.OnApplyTemplate();
        }

        protected override void PrepareContainerForItemOverride(DependencyObject element, object item)
        {
            base.PrepareContainerForItemOverride(element, item);

            if (item is IGroupHeader && GroupHeaderTemplate != null)
            {
                var ListBoxItem = element as ListBoxItem;
                if(ListBoxItem!=null)
                {
                    ListBoxItem.ContentTemplate = GroupHeaderTemplate;
                }
            }
        }

        public ContentControl GroupTitleArea
        {
            get { return groupTitleArea; }
            set { groupTitleArea = value; }
        }



        public DataTemplate GroupHeaderTemplate
        {
            get { return (DataTemplate)GetValue(GroupHeaderTemplateProperty); }
            set { SetValue(GroupHeaderTemplateProperty, value); }
        }

        // Using a DependencyProperty as the backing store for GroupHeaderTemplate.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty GroupHeaderTemplateProperty =
            DependencyProperty.Register("GroupHeaderTemplate", typeof(DataTemplate), typeof(XGroupingListBox), null);

        
    }
}
